<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>计算器</title>
    <style>
        body {
            background-color: #f0f0f0;
            font-family: Arial, sans-serif;
        }

        #top {
            width: 450px;
            height: 50px;
            margin: auto;
            background-color: #7b9ed9;
            border-radius: 10px 10px 0 0;
            display: flex;
            align-items: center;
        }

        #calc-title {
            font-size: 22px;
            color: white;
            margin-left: 20px;
        }

        #display {
            width: 445px;
            margin: auto;
            background-color: white;
            border: solid 3px #7b9ed9;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            text-align: right;
            padding: 10px;
            font-size: 36px;
        }

        #button {
            width: 450px;
            margin: auto;
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-gap: 5px;
        }

        #button div {
            height: 80px;
            background-color: #a9cce3;
            line-height: 80px;
            text-align: center;
            font-size: 28px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        #button div:hover {
            background-color: #7b9ed9;
        }

        #button div:active {
            background-color: #6492c5;
        }
    </style>
</head>

<body>
<div id="top">
    <div id="calc-title">计算器by李唯戬</div>
</div>
<div id="display">0</div>
<div id="button">
    <div onclick="clearresult()">AC</div>
    <div onclick="clickOperator('/')">÷</div>
    <div onclick="clickOperator('*')">x</div>
    <div onclick="del()">删除</div>
    <div onclick="clickNumber(7)">7</div>
    <div onclick="clickNumber(8)">8</div>
    <div onclick="clickNumber(9)">9</div>
    <div onclick="clickOperator('%')">%</div>
    <div onclick="clickNumber(4)">4</div>
    <div onclick="clickNumber(5)">5</div>
    <div onclick="clickNumber(6)">6</div>
    <div onclick="clickOperator('-')">-</div>
    <div onclick="clickNumber(1)">1</div>
    <div onclick="clickNumber(2)">2</div>
    <div onclick="clickNumber(3)">3</div>
    <div onclick="clickOperator('+')">+</div>
    <div onclick="clickOperator('sqrt')">√</div>
    <div onclick="clickNumber(0)">0</div>
    <div onclick="clickPoint()">.</div>
    <div onclick="doCalc()">=</div>
</div>

<script>
    let currentInput = '';
    let operator = '';
    let previousInput = '';

    function clickNumber(num) {
        currentInput += num.toString();
        updateDisplay();
    }

    function clickPoint() {
        if (!currentInput.includes('.')) {
            currentInput += '.';
            updateDisplay();
        }
    }

    function clearresult() {
        currentInput = '';
        operator = '';
        previousInput = '';
        updateDisplay();
    }

    function del() {
        currentInput = currentInput.slice(0, -1);
        updateDisplay();
    }

    function clickOperator(op) {
        if (op === '-') {
            if (currentInput === '') {
                currentInput = '-';
            } else if (previousInput !== '' && currentInput !== '') {
                doCalc();
                operator = op;
            } else {
                operator = op;
            }
        } else {
            if (currentInput === '' && previousInput === '') return;

            if (previousInput !== '' && currentInput !== '') {
                doCalc();
            }

            if (currentInput !== '') {
                operator = op;
                previousInput = currentInput;
                currentInput = '';
            } else {
                operator = op;
            }
        }

        updateDisplay();
    }

    function doCalc() {
        if (currentInput === '' && previousInput === '') return;

        let a = parseFloat(previousInput);
        let b = parseFloat(currentInput);

        let operation;

        switch (operator) {
            case '+':
                operation = 'add';
                break;
            case '-':
                operation = 'subtract';
                break;
            case '*':
                operation = 'multiply';
                break;
            case '/':
                operation = 'divide';
                break;
            case '%':
                operation = 'modulo';
                break;
            case 'sqrt':
                operation = 'sqrt';
                break;
            default:
                return;
        }

        let url = `http://localhost:8080/calculator/calculate?operation=${encodeURIComponent(operation)}&a=${a}` + (b ? `&b=${b}` : '');

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    return response.text().then(errorText => {
                        let errorData;
                        try {
                            errorData = JSON.parse(errorText);
                        } catch (e) {
                            errorData = { message: '未知错误', status: 500 };
                        }
                        throw new Error(errorData.message || '未知错误');
                    });
                }
                return response.text();
            })
            .then(data => {
                currentInput = parseFloat(data);
                previousInput = '';
                operator = '';

                // 清空展示区域
                updateDisplay(); // 在计算后清空展示区域
                currentInput = ''; // 为下一次输入做准备
            })
            .catch(error => {
                console.error("错误:", error.message);
                alert("错误: " + error.message);
            });
    }

    function updateDisplay() {
        const display = document.getElementById('display');
        if (previousInput !== '') {
            display.innerText = previousInput + ' ' + operator + ' ' + (currentInput || '');
        } else {
            display.innerText = currentInput || '0';
        }
    }
</script>
</body>
</html>